#include "TCP.h"
#include<poll.h>

int main(int argc,char **argv)
{
    int sockfd;
    int clientfd;
    int maxfd;
    int n_r;
    socklen_t len;
  
    char msg[1024];
    struct sockaddr_in s_addr;
    struct sockaddr_in c_addr;
    
    sockfd=TCP_server_create();
    struct pollfd fds[100];
    for(int i=0;i<100;i++)
    {
        fds[i].fd=-1;
    }
    fds[0].fd=sockfd;
    fds[0].events=POLLIN;
    
    while(1)
    {
        int rnum=poll(fds,100,-1);
        if(fds[0].events==fds[0].revents)
        {
            len=sizeof(struct sockaddr_in);
            clientfd=accept(sockfd,(struct sockaddr*)&c_addr,&len);
            if(clientfd<0)
            {
                if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
                {
                    perror("accept error\n");
                    exit(1);
                }
                continue;
            }
            for(int i=0;i<100;i++)
            {
                if(fds[i].fd==-1)
                {
                    fds[i].fd=clientfd;
                    fds[i].events=POLLIN;
                    break;
                }
            }
            if(--rnum<=0)
            {
                continue;
            }
        }
        for(int i=1;i<100;i++)
        {
            if(fds[i].fd!=-1)
            {
                if(fds[i].events==fds[i].revents)
                {
                    int fd=fds[i].fd;
                    memset(msg,0,1024);
                    int r_n=read(fd,msg,sizeof(msg));
                    if(r_n<0)
                    {
                        perror("read client error\n");
                        fds[i].fd=-1;
                    }
                      if(r_n==0)
                    {
                        perror("client close\n");
                        fds[i].fd=-1;
                    }
                    printf("recv %s\n",msg);
                    write(fd,msg,strlen(msg));
                    if(--rnum<=0)
                    {
                        break;
                    }
                }
            }
        }
        
    }

   
    return 0;
}